package com.uniledger.commonlib.easymoney;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.AppCompatTextView;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.RelativeSizeSpan;
import android.util.AttributeSet;

import com.uniledger.commonlib.R;
import com.uniledger.commonlib.util.DisplayUtil;

import java.text.DecimalFormat;
import java.util.Currency;
import java.util.Locale;

/**
 * The TextView widget for support of money requirements like currency, number formatting, comma formatting etc.
 * <p>
 * Add com.wajahatkarim3.easymoneywidgets.EasyMoneyTextView into your XML layouts and you are done!
 * For more information, check http://github.com/wajahatkarim3/EasyMoney-Widgets
 *
 * @author Wajahat Karim (http://wajahatkarim.com)
 * @version 1.0.0 01/20/2017
 */
public class EasyMoneyTextView extends AppCompatTextView {

    private String _currencySymbol;
    private boolean _showCurrency;
    private boolean _showCommas;
    private int rate;

    public EasyMoneyTextView(Context context) {
        super(context);
        initView(context, null);
    }

    public EasyMoneyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context, attrs);
    }

    private void initView(Context context, AttributeSet attrs) {

        // Setting Default Parameters
        _currencySymbol = getCountryZipCode(context);
        _showCurrency = true;
        _showCommas = true;

        // Check for the attributes
        if (attrs != null) {
            // Attribute initialization
            final TypedArray attrArray = context.obtainStyledAttributes(attrs, R.styleable.EasyMoneyWidgets, 0, 0);
            try {
                String currnecy = attrArray.getString(R.styleable.EasyMoneyWidgets_currency_symbol);

                if (currnecy == null)
                    currnecy = getCountryZipCode(context);

                setCurrencySymbol(currnecy);
                _showCurrency = attrArray.getBoolean(R.styleable.EasyMoneyWidgets_show_currency, true);
                _showCommas = attrArray.getBoolean(R.styleable.EasyMoneyWidgets_show_commas, true);
            } finally {
                attrArray.recycle();
            }
        }
    }

    /*
     * 获取国家码
     * */
    public static String getCountryZipCode(Context context)
    {
        String CountryZipCode = "";
        Locale locale = context.getResources().getConfiguration().locale;
        CountryZipCode = locale.getCountry();

        return CountryZipCode;
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        setValue(getText().toString());
    }

    private String getDecoratedStringFromNumber(long number) {
        String numberPattern = "#,###,###,###";
        String decoStr = "";

        DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault());
        if (_showCommas && !_showCurrency)
            formatter.applyPattern(numberPattern);
        else if (_showCommas && _showCurrency)
            formatter.applyPattern(_currencySymbol + " " + numberPattern);
        else if (!_showCommas && _showCurrency)
            formatter.applyPattern(_currencySymbol + " ");
        else if (!_showCommas && !_showCurrency) {
            decoStr = number + "";
            return decoStr;
        }

        decoStr = formatter.format(number);

        return decoStr;
    }

    private void setValue(String valueStr) {

        if (TextUtils.isEmpty(valueStr))
            return;

        String backupString = valueStr;
        try {
            String originalString = valueStr;

            long longval = 0;

            originalString = getValueString();
            longval = (Long.parseLong(originalString));
            String formattedString = getDecoratedStringFromNumber(longval);

            //setting text after format to EditText
            setSpanText(formattedString);

        } catch (NumberFormatException nfe) {
            nfe.printStackTrace();
            setSpanText(backupString);

            String valStr = getValueString();

            if (valStr.equals("")) {
                long val = 0;
                setSpanText(getDecoratedStringFromNumber(val));
            } else {
                // Some decimal number
                if (valStr.contains(".")) {
                    if (valStr.indexOf(".") == valStr.length() - 1) {
                        // decimal has been currently put
                        String front = getDecoratedStringFromNumber(Long.parseLong(valStr.substring(0, valStr.length() - 1)));
                        setSpanText(front + ".");
                    } else {
                        String[] nums = getValueString().split("\\.");
                        String front = getDecoratedStringFromNumber(Long.parseLong(nums[0]));
                        setSpanText(front + "." + nums[1]);
                    }
                }
            }
        }
    }

    /**
     * Get the value of the text without any commas and currency.
     * For example, if the edit text value is $ 1,34,000.60 then this method will return 134000.60
     *
     * @return A string of the raw value in the text field
     */
    public String getValueString() {

        String string = getText().toString();

        if (string.contains(",")) {
            string = string.replace(",", "");
        }
        if (string.contains(" ")) {
            string = string.substring(string.indexOf(" ") + 1, string.length());
        }
        return string;
    }

    /**
     * Get the value of the text with formatted commas and currency.
     * For example, if the edit text value is $ 1,34,000.60 then this method will return exactly $ 1,34,000.60
     *
     * @return A string of the text value in the text field
     */
    public String getFormattedString() {
        setValue(getText().toString());
        return getText().toString();
    }

    /**
     * Set the currency symbol for the edit text. (Default is US Dollar $).
     *
     * @param newSymbol the new symbol of currency in string
     */
    public void setCurrencySymbol(String newSymbol) {
        setCurrencySymbol(newSymbol, R.drawable.ic_common_aed);
    }

    public void setSizeCurrencySymbol(String newSymbol) {
        setSizeCurrencySymbol(newSymbol, R.drawable.ic_common_aed, 12);
    }

    public void setCurrencyBlackSymbol(String newSymbol) {
        setCurrencySymbol(newSymbol, R.drawable.ic_common_black_aed);
    }

    /**
     * 12号字
     * @param newSymbol
     * @param res
     */
    public void setCurrencyWithdrawSymbol(String newSymbol, int res) {
        setSizeCurrencySymbol(newSymbol, res, 12);
    }

    public void setCurrencySecondarySymbol(String newSymbol, int res) {
        setCurrencySymbol(newSymbol, res);
    }

    /**
     * Set the currency symbol for the edit text. (Default is US Dollar $).
     *
     * 固定大小
     * @param newSymbol the new symbol of currency in string
     */
    public void setCurrencySymbol(String newSymbol, int res) {
        if (TextUtils.equals(newSymbol, "AED")
                || TextUtils.equals("PHP", newSymbol)
                || TextUtils.equals("USD", newSymbol)) {
            Drawable drawable = getContext().getResources().getDrawable(res);
            setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
            hideCurrencySymbol();
        } else {
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            _currencySymbol = newSymbol.toUpperCase();
            showCurrencySymbol();
        }
    }

    /**
     * 根据字体大小需要设置货币符号图片大小
     *
     * @param newSymbol
     * @param res
     * @param frontSize
     */
    public void setSizeCurrencySymbol(String newSymbol, int res, int frontSize) {
        if (TextUtils.equals(newSymbol, "AED")
                || TextUtils.equals("PHP", newSymbol)
                || TextUtils.equals("USD", newSymbol)) {
            Drawable drawable = getContext().getResources().getDrawable(res);
            int size = DisplayUtil.dip2px(getContext(), frontSize);
            drawable.setBounds(0, 0, size, size);
            setCompoundDrawables(drawable, null, null, null);
            hideCurrencySymbol();
        } else {
            setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
            _currencySymbol = newSymbol.toUpperCase();
            showCurrencySymbol();
        }
    }


    /**
     * Set the currency symbol for the edit text. (Default is US Dollar $).
     *
     * @param locale the locale of new symbol. (Defaul is Locale.US)
     */
    public void setCurrencySymbol(Locale locale) {
        setCurrencySymbol(Currency.getInstance(locale).getSymbol());
    }

    /**
     * Set the currency symbol for the edit text. (Default is US Dollar $).
     *
     * @param currency the currency object of new symbol. (Defaul is Locale.US)
     */
    public void setCurrencySymbol(Currency currency) {
        setCurrencySymbol(currency.getSymbol());
    }

    public void setShowCurrency(boolean value) {
        _showCurrency = value;
        setValue(getText().toString());
    }

    /**
     * Whether currency is shown in the text or not. (Default is true)
     *
     * @return true if the currency is shown otherwise false.
     */
    public boolean isShowCurrency() {
        return _showCurrency;
    }

    /**
     * Shows the currency in the text. (Default is shown).
     */
    public void showCurrencySymbol() {
        setShowCurrency(true);
    }

    /**
     * Hides the currency in the text. (Default is shown).
     */
    public void hideCurrencySymbol() {
        setShowCurrency(false);
    }

    /**
     * Shows the commas in the text. (Default is shown).
     */
    public void showCommas() {
        _showCommas = true;
        setValue(getText().toString());
    }

    /**
     * Hides the commas in the text. (Default is shown).
     */
    public void hideCommas() {
        _showCommas = false;
        setValue(getText().toString());
    }

    public void setMoneyText(String money) {
        setSpanText(money);
        setValue(getText().toString());
    }

    private void setSpanText(CharSequence text) {
        if (text.length() > 1) {
            SpannableStringBuilder builder = new SpannableStringBuilder(text);
            builder.setSpan(new RelativeSizeSpan(1f), 0, 0 + _currencySymbol.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
            setText(builder);
        } else {
            setText(text);
        }
    }
}
